package br.com.r1.observer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class FileMediaObserver implements Observer {

	private Observable observable;
	private BufferedWriter bw;
	private BufferedReader br;
	private List<String> content;
	private final File file = new File("C:/Users/sunwebdeveloper/fileMediaObserver.txt");
	
	
	public FileMediaObserver(Observable observable) {
		try {
			this.observable = observable;
			this.observable.addObserver(this);
			this.br = new BufferedReader(new FileReader(file));
			this.bw = new BufferedWriter(new FileWriter(file));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void readContent(){
		try {
			if(br!=null){
				String linha = br.readLine();
				while(linha!=null){
					content.add(linha);
					linha = br.readLine();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	@Override
	public void update(Observable o, Object arg) {
		try {
			readContent();
			if(content!=null && content.size()>0){
				for(String s:content){
					bw.write(s+"/n");
				}
			}
			bw.write(((PainelDeControleObserver)o).getQuote().toString()+"\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void removeObserver(){
		this.observable.deleteObserver(this);
	}
	
	public void flushFile() throws IOException{
		this.bw.flush();
		this.bw.close();
		this.br.close();
	}
}